const http=require('http');
const fs=require('fs');
const mysql=require('mysql');
const io=require('socket.io');
const url=require('url');

let db=mysql.createPool({host:'localhost',user:'root',database:'20180326'});


let httpServer=http.createServer((req,res)=>{
    let {pathname,query}=url.parse(req.url,true);
    let {username,password}=query;
    if(pathname=='/logup'){
        if(!/^\w{6,32}$/.test(username)){
            res.write(JSON.stringify({code:1,msg:'用户名格式错误'}));
            res.end()
        }else if(!/^.{6,32}$/.test(password)){
            res.write(JSON.stringify({code:1,msg:'密码格式错误'}));
            res.end()
        }else{

            db.query(`SELECT * FROM user_table WHERE username='${username}'`,(err,data)=>{
                if(err){
                    res.write(JSON.stringify({code:1,msg:'数据库出错'}));
                    res.end()
                }else if(data.length>0){
                    res.write(JSON.stringify({code:1,msg:'用户名已注册'}));
                    res.end()
                }else{
                    db.query(`INSERT INTO user_table (username,password,online) VALUES ('${username}','${password}',0)`,err=>{
                        if(err){
                            res.write(JSON.stringify({code:1,msg:'数据库出错'}));
                            res.end()
                        }else{
                            res.write(JSON.stringify({code:1,msg:'恭喜你注册成功'}));
                            res.end()
                        }
                    })
                }
            })
        }


    }else if(pathname=='/login'){
        if(!/^\w{6,32}$/.test(username)){
            res.write(JSON.stringify({code:1,msg:'用户名格式错误'}));
            res.end();
        }else if(!/^.{6,32}$/.test(password)){
            res.write(JSON.stringify({code:1,msg:'密码格式错误'}));
            res.end();
        }else{
            db.query(`SELECT id,password FROM user_table WHERE username='${username}'`,(err,data)=>{
                if(err){
                    res.write(JSON.stringify({code:1,msg:'数据库出错'}));
                    res.end();
                }else if(data.length==0){
                    res.write(JSON.stringify({code:1,msg:'用户名不存在'}));
                    res.end();
                }else if(data[0].password!=password){
                    res.write(JSON.stringify({code:1,msg:'用户名或密码错误'}));
                    res.end();
                }else{
                    db.query(`UPDATE user_table SET online=1 WHERE id=${id}`,err=>{
                        res.write(JSON.stringify({code:0,msg:'用户登录成功'}));
                        res.end();
                    })
                }
            })
        }
    }else{
        fs.readFile(`www${pathname}`,(err,data)=>{
            if(err){
                res.writeHeader(404);
                res.write('NOT FOUND');
            }else{
                res.write(data);
            }
            res.end();
        })
    }



})

httpServer.listen(8080);
